import java.io.IOException;
import java.net.*;
import java.util.Scanner;

public class Client {
    private DatagramSocket socket = null;
    private String serverIP = "";
    private int serverPort = 0;
    public Client(String ip, int port) throws SocketException {
        socket = new DatagramSocket();
        //UDP不会存储对端的信息，需要在应用程序中把对端的信息记录下来
        this.serverIP = ip;
        this.serverPort = port;
    }

    public void start() throws IOException {
        System.out.println("客户端请启动");
        Scanner scanner = new Scanner(System.in);
        while(true){
            //1.输入请求
            System.out.print("-> ");
            String req = scanner.next();
            //2.发给服务器
            DatagramPacket request = new DatagramPacket(req.getBytes(),req.getBytes().length,
                    InetAddress.getByName(serverIP),serverPort);
            socket.send(request);
            //3.获取响应
            DatagramPacket res = new DatagramPacket(new byte[1024],1024);
            socket.receive(res);
            //4.显示响应
            String response = new String(res.getData(),0,res.getLength());
            System.out.println(response);
        }
    }
    public static void main(String[] args) throws IOException {
        Client client = new Client("10.162.153.3",9090);
        client.start();
    }
}
